package com.xu.system.auth.pwd;

import com.xu.base.enums.ResponseCodeEnum;
import com.xu.base.utils.AssertUtils;
import com.xu.security.model.OnlineUser;
import com.xu.security.token.TokenService;
import jakarta.annotation.Resource;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;


/**
 * 密码认证器
 * @Author: 许乾伟
 * @Date: 2024/2/27 14:25
 */
@Component
public class PwdAuthenticationProvider implements AuthenticationProvider {
    @Resource
    PwdUserDetailsService pwdUserDetailsService;
    @Resource
    PasswordEncoder passwordEncoder;
    @Resource
    TokenService tokenService;
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        UsernamePasswordAuthenticationToken accountPassToken = (UsernamePasswordAuthenticationToken) authentication;
        String account = accountPassToken.getPrincipal().toString();
        String pwd = accountPassToken.getCredentials().toString();
        OnlineUser userDetails = (OnlineUser) pwdUserDetailsService.loadUserByUsername(account);
        AssertUtils.isFalse(passwordEncoder.matches(pwd,userDetails.getPassword()), ResponseCodeEnum.AUTH_FAILED,"密码错误");
        //创建token
        tokenService.createToken(userDetails);
        return new UsernamePasswordAuthenticationToken(userDetails,accountPassToken.getCredentials(),userDetails.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }
}
